/**
 * Request模式预约测试
 */

import type { AppointmentManagement } from '../src/shared/types/'
import type { AppConfig } from '../src/shared/types/config'

// 在导入其他模块前先加载 .env 文件
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { isGlobalCancelRequested } from '../src/main/booking/engine-registry'
import { RequestBookingStrategy } from '../src/main/booking/request-strategy'
import { loadConfig, updateConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'

// 加载 .env 文件（在模块导入后立即执行）
;

(() => {
  try {
    const envPath = resolve(__dirname, '../.env')
    const envContent = readFileSync(envPath, 'utf-8')
    envContent.split('\n').forEach((line) => {
      const trimmed = line.trim()
      if (trimmed && !trimmed.startsWith('#')) {
        const [key, ...valueParts] = trimmed.split('=')
        if (key && valueParts.length > 0) {
          const value = valueParts.join('=').trim().replace(/^["']|["']$/g, '')
          process.env[key.trim()] = value
        }
      }
    })
  }
  catch (error) {
    // .env 文件不存在时忽略错误
    if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
      console.warn('加载 .env 文件失败:', error)
    }
  }
})()

/**
 * 创建测试用的预约数据
 */
function createTestAppointment(overrides?: Partial<AppointmentManagement>): AppointmentManagement {
  const now = new Date()
  return {
    id: Math.floor(Math.random() * 1000000),
    sequence_number: `TEST-REQ-${Date.now()}`,
    passport_number: 'CE2345678', // 测试用护照号
    license_number: '440123199012011234', // 测试用驾照号
    full_name: '策小市',
    email: 'zhanzr516688cexiaoshi@2925.com',
    phone_number: '21234567', // 香港电话号码格式（8位，以2开头）
    issuing_country: 'CN',
    issuing_authority: 'GD',
    service_type: 'DI',
    preferred_dates: JSON.stringify([]), // 不指定日期，让系统自动选择
    preferred_times: JSON.stringify([]),
    priority: 2,
    remarks: 'Request模式测试预约',
    is_placeholder: false,
    is_monitor: false,
    appointment_status: 'pending',
    office_code: 'HKLO',
    booking_mode: 'request',
    retry_count: 0,
    created_at: now,
    updated_at: now,
    ...overrides,
  }
}

/**
 * 单个预约测试
 */
async function testSingleRequestBooking(): Promise<void> {
  console.log('='.repeat(60))
  console.log('Request模式 - 单个预约测试')
  console.log('='.repeat(60))

  try {
    await loadConfig()
    await setupLogger()

    // 确保使用单进程模式
    await updateConfig({
      booking: {
        multiprocess: {
          enabled: false,
        },
      },
    } as Partial<AppConfig>)

    const strategy = new RequestBookingStrategy()
    const appointment = createTestAppointment()

    console.log('测试数据：')
    console.log(`  护照号: ${appointment.passport_number}`)
    console.log(`  驾照号: ${appointment.license_number}`)
    console.log(`  姓名: ${appointment.full_name}`)
    console.log(`  电话: ${appointment.phone_number}`)
    console.log(`  办事处: ${appointment.office_code}`)
    console.log()

    console.log('开始执行预约（Request 模式）...')
    const startTime = Date.now()

    const result = await strategy.book(appointment, {
      timeoutMs: 120000, // 2分钟超时
      preferredDates: [], // 自动选择第一个可用日期
      preferredTimes: [],
    })

    const duration = Date.now() - startTime

    console.log()
    console.log('='.repeat(60))
    if (result.success) {
      console.log('✓ 预约成功！')
      console.log(`  参考编号: ${result.referenceNumber}`)
      if (result.selectedDate) {
        console.log(`  预约日期: ${result.selectedDate}`)
      }
      if (result.selectedTimeslot) {
        console.log(`  预约时段: ${result.selectedTimeslot}`)
      }
    }
    else {
      console.log('✗ 预约失败')
      console.log(`  错误: ${result.error}`)
    }
    console.log(`  耗时: ${(duration / 1000).toFixed(2)} 秒`)
    console.log('='.repeat(60))

    process.exit(result.success ? 0 : 1)
  }
  catch (error) {
    console.error('测试失败:', error)
    process.exit(1)
  }
}

/**
 * 多个预约测试
 */
async function testMultipleRequestBooking(count: number): Promise<void> {
  console.log('='.repeat(60))
  console.log(`Request模式 - 多个预约测试 (${count}个)`)
  console.log('='.repeat(60))

  try {
    await loadConfig()
    await setupLogger()

    // 确保使用单进程模式
    await updateConfig({
      booking: {
        multiprocess: {
          enabled: false,
        },
      },
    } as Partial<AppConfig>)

    const strategy = new RequestBookingStrategy()
    const results: Array<{ success: boolean, reference?: string, error?: string, duration: number }> = []

    for (let i = 1; i <= count; i++) {
      if (isGlobalCancelRequested()) {
        console.log('预约已被停止')
        break
      }

      console.log()
      console.log(`预约 ${i}/${count}`)
      console.log('-'.repeat(60))

      const appointment = createTestAppointment({
        sequence_number: `TEST-REQ-${Date.now()}-${i}`,
      })

      const startTime = Date.now()
      const result = await strategy.book(appointment, {
        timeoutMs: 120000,
        preferredDates: [],
        preferredTimes: [],
      })
      const duration = Date.now() - startTime

      results.push({
        success: result.success,
        reference: result.referenceNumber,
        error: result.error,
        duration,
      })

      if (result.success) {
        console.log(`  ✓ 成功 - 参考编号: ${result.referenceNumber}`)
      }
      else {
        console.log(`  ✗ 失败 - ${result.error}`)
      }
      console.log(`  耗时: ${(duration / 1000).toFixed(2)} 秒`)
    }

    console.log()
    console.log('='.repeat(60))
    console.log('测试总结')
    console.log('='.repeat(60))
    const successCount = results.filter(r => r.success).length
    const failCount = results.length - successCount
    const avgDuration = results.reduce((sum, r) => sum + r.duration, 0) / results.length

    console.log(`  成功: ${successCount}/${results.length}`)
    console.log(`  失败: ${failCount}/${results.length}`)
    console.log(`  平均耗时: ${(avgDuration / 1000).toFixed(2)} 秒`)

    if (successCount > 0) {
      console.log('\n  成功的预约:')
      results.filter(r => r.success).forEach((r, i) => {
        console.log(`    ${i + 1}. ${r.reference} (${(r.duration / 1000).toFixed(2)}秒)`)
      })
    }

    if (failCount > 0) {
      console.log('\n  失败的预约:')
      results.filter(r => !r.success).forEach((r, i) => {
        console.log(`    ${i + 1}. ${r.error} (${(r.duration / 1000).toFixed(2)}秒)`)
      })
    }

    console.log('='.repeat(60))

    process.exit(failCount === 0 ? 0 : 1)
  }
  catch (error) {
    console.error('测试失败:', error)
    process.exit(1)
  }
}

// 主函数
async function main() {
  const count = Number.parseInt(process.argv[2] || '1', 10)

  if (count === 1) {
    await testSingleRequestBooking()
  }
  else {
    await testMultipleRequestBooking(count)
  }
}

main().catch((error) => {
  console.error('执行失败:', error)
  process.exit(1)
})
